﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Extensions;

namespace ERPStore.NewsLetters.MessageReaders
{
	public class NewsLetterSentMessageReader : Ariane.MessageReaderBase<Events.NewsLetterSentEventMessage>
	{
		public NewsLetterSentMessageReader(
			ERPStore.Logging.ILogger logger
			)
		{
			this.Logger = logger;
		}

		protected ERPStore.Logging.ILogger Logger { get; private set; }
		protected Services.NewsLettersService NewsLetterService 
		{
			get
			{
				return ERPStore.GlobalConfiguration.Configuration.DependencyResolver.GetService<Services.NewsLettersService>();
			}
		}

		public override void ProcessMessage(Events.NewsLetterSentEventMessage eventMessage)
		{
			Logger.Debug("newsletters sent for {0} : {1}", eventMessage.EmailRecipientId, eventMessage.FaultReason);

			var data = NewsLetterService.GetEmailRecipientById(eventMessage.EmailRecipientId);
			var emailRecipient = AutoMapper.Mapper.Map<Models.EmailRecipient>(data);

			var sendResult = new Models.EmailSentResult();
			sendResult.CampaignId = eventMessage.CampaignId;
			sendResult.EmailRecipient = emailRecipient;
			sendResult.SentDate = DateTime.Now;
			sendResult.FaultReason = eventMessage.FaultReason;

			NewsLetterService.SaveEmailSent(sendResult);
		}
	}
}
